#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "global.h"
#include "clickedlabel.h"
RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);

    initHttpHandlers();

    ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
    ui->confirm_lineEdit->setEchoMode(QLineEdit::Password);

    ui->error_label->setProperty("state","normal");
    repolish(ui->error_label);

    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reg_mod_finish,this,&RegisterDialog::slot_reg_mod_finish);

    connect(ui->user_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkUserVaild() ;
    });
    connect(ui->email_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkEmailVaild() ;
    });
    connect(ui->captcha_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkVarifyVaild() ;
    });
    connect(ui->pwd_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkPassVaild() ;
    });
    connect(ui->confirm_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkConfirmVaild();
    });


    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->confirm_visible->setCursor(Qt::PointingHandCursor);

    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible","visible_hover","");
    ui->confirm_visible->SetState("unvisible","unvisible_hover","","visible","visible_hover","");

    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        auto state =ui->pass_visible->GetCurState();
        if(state==ClickLbState::Normal){
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
        }
        else{
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
    connect(ui->confirm_visible,&ClickedLabel::clicked,this,[this](){
        auto state =ui->confirm_visible->GetCurState();
        if(state==ClickLbState::Normal){
            ui->confirm_lineEdit->setEchoMode(QLineEdit::Password);
        }
        else{
            ui->confirm_lineEdit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    _countdown_timer=new QTimer(this);
    connect(_countdown_timer,&QTimer::timeout,this,[this](){
        if(_countdown<=0){
            _countdown=5;
            _countdown_timer->stop();
            emit sigSwitchLogin();
            return;
        }
        _countdown--;
        auto str=QString("注册成功，%1 s后返回登录页面").arg(_countdown);
        ui->tip_label->setText(str);
    });
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::initHttpHandlers()
{
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE,[this](QJsonObject jsonObj){
        int error=jsonObj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS){
            showTip(tr("调用参数错误"),false);
            return;
        }
        auto email=jsonObj["email"].toString();
        showTip(tr("验证码已发送到邮箱"),true);
        //email值
        qDebug()<<"email is"<<email;
    });

    _handlers.insert(ReqId::ID_REG_USER,[this](QJsonObject jsonObj){
        int error =jsonObj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS){
            showTip(tr("调用参数错误"),false);
            return;
        }

        auto email=jsonObj["email"].toString();
        showTip(tr("注册成功"),true);
        qDebug()<<"email is"<<email;
        qDebug()<<"uid is "<<jsonObj["uid"].toString();
        ChangeTipPage();
    });
}

void RegisterDialog::on_captcha_btn_clicked()
{
    auto email=ui->email_lineEdit->text();
    bool match=checkEmailVaild();
    if(match){
        //发送验证码
        qDebug()<<"发送验证码";
        QJsonObject json_obj;
        json_obj["email"]=email;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_varifyCode"),
                                            json_obj,ReqId::ID_GET_VARIFY_CODE,Modules::REGISTERMOD);
    }

}

void RegisterDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err!=ErrorCodes::SUCCESS){
        showTip(tr("网络请求连接错误"),false);
        return;
    }
    //解析json字符，由网络字节转化为json类型
    QJsonDocument jsonDoc=QJsonDocument::fromJson(res.toUtf8());
    //json解析错误
    if(jsonDoc.isNull()){
        showTip("json解析错误",false);
        return;
    }
    //json解析错误
    if(!jsonDoc.isObject()){
        showTip("json解析错误",false);
        return;
    }
    QJsonObject jsonObj=jsonDoc.object();

    //调用对应逻辑。。。。。。。。。。
    _handlers[id](jsonObj);

    return;
}

void RegisterDialog::showTip(QString str, bool b_ok)
{
    if(b_ok){
        ui->error_label->setProperty("state","normal");
    }
    else{
        ui->error_label->setProperty("state","err");
    }
    ui->error_label->setText(str);
    repolish(ui->error_label);
}

bool RegisterDialog::checkUserVaild()
{
    if(ui->user_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,tr("用户名不能为空"));
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool RegisterDialog::checkEmailVaild()
{
    auto email=ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match=regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,tr("邮箱不正确"));
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool RegisterDialog::checkPassVaild()
{
    auto pass=ui->pwd_lineEdit->text();
    if(pass.length()<6||pass.length()>15){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("密码长度应为6~15"));
        return false;
    }
    //正则表达式设置密码
    QRegularExpression regExp("[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match =regExp.match(pass).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("不能包含非法字符"));
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    auto confirm=ui->confirm_lineEdit->text();
    if(confirm!=pass){
        AddTipErr(TipErr::TIP_CONFIRM_ERR,"确认密码和密码不相同");
        return false;
    }else{
        DelTipErr(TipErr::TIP_CONFIRM_ERR);
    }

    return true;
}

bool RegisterDialog::checkVarifyVaild()
{
    auto varify=ui->captcha_lineEdit->text();
    if(varify.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR,"验证码不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

bool RegisterDialog::checkConfirmVaild()
{
    auto confirm=ui->confirm_lineEdit->text();
    if(confirm!=ui->pwd_lineEdit->text()){
        AddTipErr(TipErr::TIP_CONFIRM_ERR,"确认密码和密码不相同");
        return false;
    }
    DelTipErr(TipErr::TIP_CONFIRM_ERR);
    return true;
}




void RegisterDialog::on_confirm_btn_clicked()
{

    if(!checkUserVaild()){
        return;
    }
    if(!checkEmailVaild()){
        return;
    }
    if(!checkPassVaild()){
        return;
    }
    if(!checkVarifyVaild()){
        return;
    }

    //发送http请求注册用户
    QJsonObject json_obj;
    json_obj["user"]=ui->user_lineEdit->text();
    json_obj["email"]=ui->email_lineEdit->text();
    json_obj["passwd"]=xorString(ui->pwd_lineEdit->text());
    json_obj["confirm"]=xorString(ui->confirm_lineEdit->text());
    json_obj["varify"]=ui->captcha_lineEdit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_register"),
                                        json_obj,ReqId::ID_REG_USER,Modules::REGISTERMOD);
}

void RegisterDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te]=tips;
    showTip(tips,false);
}

void RegisterDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->error_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

void RegisterDialog::ChangeTipPage()
{
    _countdown_timer->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);
    _countdown_timer->start(1000);
}


void RegisterDialog::on_return_btn_clicked()
{
    _countdown_timer->stop();
    emit sigSwitchLogin();
}


void RegisterDialog::on_cancel_btn_clicked()
{
    _countdown_timer->stop();
    emit sigSwitchLogin();
}

